/*
 *
 *
Copyright (c) 1998-2001 Aristar, Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

3. The end-user documentation included with the redistribution, if any,
must include the following acknowledgment:

"This product includes software developed by Aristar, Inc. (http://www.aristar.com/)."

Alternately, this acknowledgment may appear in the software itself, if and
wherever such third-party acknowledgments normally appear.

4. The names "Dialect" and "Aristar, Inc." must not be used to endorse or
promote products derived from this software without prior written permission.
For written permission, please contact info@aristar.com.

5. Products derived from this software may not be called "Dialect", nor may
"Dialect" appear in their name, without prior written permission of Aristar, Inc.

THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
ARISTAR, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

This software consists of voluntary contributions made by many individuals
on behalf of Aristar, Inc.  For more information on Aristar, Inc.,
please see <http://www.aristar.com/>.

Portions of this software are based upon software freely available and
written by individuals not associated with Aristar, Inc.  Copyrights are
maintained in the relevant source code files.
 *
 *
 */

// QWindow.cpp : implementation file
//

#include "stdafx.h"
#include "QWindow.h"
#include "QMenuBar.h"
#include "CImplementer.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

// CQwindow needs this for WM_SYSCHAR handling (in QMenuBar.cpp)
extern VALUE g_vWndToMenu;

/////////////////////////////////////////////////////////////////////////////

CQBase::CQBase(VALUE vSelf)
{
	ASSERT(vSelf.Type() == stClassInstance);
	m_pCI = vSelf.ClassInstance();
}

VALUE CQBase::GetSelf()
{
	VALUE v;
	v.ForceCI(stClassInstance, m_pCI);
	return v;
}

/////////////////////////////////////////////////////////////////////////////
// CQWindow

static COLORREF	   g_White = RGB(255,255,255);
static COLORREF	   g_Black = RGB(0,0,0);
static COLORREF	   g_LightGray = RGB(192,192,192);
static COLORREF	   g_DarkGray = RGB(128,128,128);

CFont		   g_QEditFont;
CFont		   g_QLabelFont;

#ifdef UNDER_CE
	static COLORREF g_BackgroundColor = (COLORREF) GetSysColor(COLOR_STATIC);
#else
	static COLORREF g_BackgroundColor = (COLORREF) GetSysColor(COLOR_BTNFACE);
#endif

BOOL qWindowRegistered = FALSE;

CString qWindowClassName;

#ifdef UNDER_CE
	CBrush  qWindowBrush(GetSysColor(COLOR_STATIC));
#else
	CBrush  qWindowBrush(GetSysColor(COLOR_BTNFACE));
#endif

CQWindow::CQWindow(CString label, RECT& rc, int options, int exOptions,
				   VALUE (*pHandler) (CQWindow*, int, VALUE), VALUE vSelf)
				   :CWnd(), CQBase(vSelf)
{
	m_pHandler = pHandler;

	if (!qWindowRegistered)
	{
		qWindowRegistered = TRUE;
		qWindowClassName = AfxRegisterWndClass(
			CS_DBLCLKS |
			CS_HREDRAW |
			CS_VREDRAW |
			0,				// UINT nClassStyle,
			0,				// HCURSOR hCursor = 0,
			qWindowBrush,	// HBRUSH hbrBackground = 0,
			0				// HICON hIcon = 0
			);
/*
		#ifdef UNDER_CE
			g_BackgroundColor = (COLORREF) GetSysColor(COLOR_STATIC);
		#else
			g_BackgroundColor = (COLORREF) GetSysColor(COLOR_BTNFACE);
		#endif
*/
	g_QEditFont.CreateFont(
		-12,			// int nHeight (- == device units),
		0,				// int nWidth (0 == don't care),
		0,				// int nEscapement,
		0,				// int nOrientation,
		FW_BOLD,		// int nWeight (FW_BOLD?),
		0,				// BYTE bItalic,
		0,				// BYTE bUnderline,
		0,				// BYTE cStrikeOut,
		0,				// BYTE nCharSet,
		OUT_RASTER_PRECIS,		// BYTE nOutPrecision,
		CLIP_DEFAULT_PRECIS,	// BYTE nClipPrecision,
		DEFAULT_QUALITY,		// BYTE nQuality,
		FF_SWISS|DEFAULT_PITCH, // BYTE nPitchAndFamily,
		_T("Arial")				// LPCTSTR lpszFacename
		);

	g_QLabelFont.CreateFont(
		-11,			// int nHeight (- == device units),
		0,				// int nWidth (0 == don't care),
		0,				// int nEscapement,
		0,				// int nOrientation,
		FW_DONTCARE,	// int nWeight (FW_BOLD?),
		0,				// BYTE bItalic,
		0,				// BYTE bUnderline,
		0,				// BYTE cStrikeOut,
		0,				// BYTE nCharSet,
		OUT_RASTER_PRECIS,		// BYTE nOutPrecision,
		CLIP_DEFAULT_PRECIS,	// BYTE nClipPrecision,
		DEFAULT_QUALITY,		// BYTE nQuality,
		FF_SWISS|DEFAULT_PITCH, // BYTE nPitchAndFamily,
		_T("Arial")				// LPCTSTR lpszFacename
		);
	}

	if (options & QWS_RESIZABLE) {
		#ifdef UNDER_CE
			//options |= WS_OVERLAPPED;
			options |= (WS_POPUP | WS_CAPTION);
		#else
			options |= WS_THICKFRAME;
		#endif
	}
	else {
		#ifdef UNDER_CE
			options |= WS_OVERLAPPED;
		#else
			options |= WS_DLGFRAME;
		#endif
	}

	if (options & QWS_TITLEBAR) {
		#ifdef UNDER_CE
			//options |= WS_OVERLAPPED;
		#else

		#endif
	}
	else {
		#ifdef UNDER_CE
			//options &= ~QWS_RESIZABLE;
		#else

		#endif
		//options &= ~QWS_CLOSEBOX;
		//options &= ~QWS_MINBOX;
		//options &= ~QWS_MAXBOX;
		//options |= WS_DLGFRAME;
	}

#ifdef UNDER_CE
//#	ifdef _WIN32_WCE_PSPC
#	ifdef WIN32_PLATFORM_PSPC
		CreateEx(
			exOptions | ((options & QWS_RESIZABLE) ? WS_EX_OVERLAPPEDWINDOW : WS_EX_DLGMODALFRAME),
			qWindowClassName,		//LPCTSTR lpszClassName,
			label,					//LPCTSTR lpszWindowName,
			WS_SYSMENU | options,
			rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top,
			NULL,					//CWnd* pParentWnd,
			0,						//UINT nID,
			NULL					//CCreateContext* pContext = NULL);
			);
#	else
		CreateEx(
			exOptions |
			((options & QWS_RESIZABLE) ? WS_EX_OVERLAPPEDWINDOW : WS_EX_DLGMODALFRAME),
			qWindowClassName,		//LPCTSTR lpszClassName,
			label,					//LPCTSTR lpszWindowName,
			WS_SYSMENU |
			options,
			rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top,
			NULL,					//CWnd* pParentWnd,
			0,						//UINT nID,
			NULL					//CCreateContext* pContext = NULL);
			);
#	endif
#else
	CreateEx(
		exOptions |
		((options & QWS_RESIZABLE) ? WS_EX_OVERLAPPEDWINDOW : 0) |
		WS_EX_CONTROLPARENT,
		qWindowClassName,		//LPCTSTR lpszClassName,
		label,					//LPCTSTR lpszWindowName,
		options,						//DWORD dwStyle,
		rc,						//const RECT& rect,
		NULL,					//CWnd* pParentWnd,
		0,						//UINT nID,
		NULL					//CCreateContext* pContext = NULL);
		);
#endif
}

CQWindow::~CQWindow()
{
}


BEGIN_MESSAGE_MAP(CQWindow, CWnd)
	//{{AFX_MSG_MAP(CQWindow)
	ON_WM_CLOSE()
	ON_WM_SIZE()
	ON_WM_SHOWWINDOW()
	ON_WM_PAINT()
	ON_WM_CREATE()
	ON_WM_DESTROY()
	ON_WM_KEYDOWN()
	ON_WM_TIMER()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()


/////////////////////////////////////////////////////////////////////////////
// CQWindow message handlers

void CQWindow::OnClose()
{
	VALUE vResult = true;	// Default to allow close

	if (m_pHandler) {
		// The return value of a Dialect function defaults to
		// nil if the user doesn't specifically call return with
		// a value, therefore if the onclose() exists and doesn't
		// specifically return a true value, the window won't close.
		vResult = m_pHandler(this, QW_CLOSE, VALUE());
		if (vResult.Type() == stUndefined) vResult = true;
	}

	if (vResult.Boolean()) {
		CWnd::OnClose();
	}
}

void CQWindow::OnShowWindow(BOOL bShow, UINT nStatus)
{
	CWnd::OnShowWindow(bShow, nStatus);
	if (m_pHandler && m_pCI && (m_pCI->__get__(_T("#pQ")).Type() == stVoid)) {
		m_pHandler(this, QW_VISIBLE, (bool)(bShow == TRUE));
	}
}

void CQWindow::OnSize(UINT nType, int cx, int cy)
{
	CWnd::OnSize(nType, cx, cy);
	if (m_pHandler && m_pCI && (m_pCI->__get__(_T("#pQ")).Type() == stVoid)) {
		m_pHandler(this, QW_RESIZE, VALUE());
	}
}

void CQWindow::OnTimer(UINT nIDEvent)
{
	if (m_pHandler) {
		if (m_pHandler(this, QW_TIMER, (int)nIDEvent).Type() != stUndefined) return;
	}
	CWnd::OnTimer(nIDEvent);
}

void CQWindow::OnPaint()
{
	CPaintDC dc(this); // device context for painting

	// TODO: Add your message handler code here

	// Do not call CWnd::OnPaint() for painting messages
}

int CQWindow::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CWnd::OnCreate(lpCreateStruct) == -1)
		return -1;

	// TODO: Add your specialized creation code here

	return 0;
}

CRect CQWindow::GetSize()
{
	CRect rect;
	GetClientRect(&rect);
	return rect;
}

void CQWindow::SetSize(CRect rect)
{

}

void CQWindow::OnDestroy()
{
	CWnd::OnDestroy();
	if (m_pHandler) {
		m_pHandler(this, QW_DESTROY, VALUE());
	}
}

BOOL CQWindow::OnCommand(WPARAM wParam, LPARAM lParam)
{
	/*if ((lParam == 0) && (m_pHandler != NULL)) {
		// Menu item...
		VALUE vMenu = GetSelf().Get(_T("#lastmenu"));
		if (vMenu.Type() == stArray) {
			int index = (int)wParam - 1000;
			if (vMenu.Length() >= index) {
				VALUE vItem = vMenu[index];
				if ((vItem.Type() == stArray) && (vItem.Length() > 1)) {
					m_pHandler(this, QW_MENUSELECT, vItem[2]);
				}
				else {
					m_pHandler(this, QW_MENUSELECT, vItem);
				}
				return TRUE;
			}
		}
	}*/
	return CWnd::OnCommand(wParam, lParam);
}

BOOL CQWindow::PreTranslateMessage(MSG* pMsg)
{
	// KWN - on the pocketPC, we need to get WM_HOTKEY
	// mesages for the record button.  m_pHandler eats all
	// hotkey messages, so we have to check first to see
	// if it is the record button (we want the edit dialog to
	// get that message!)
	// NOTE: verify this doesn't break HPC and desktop...
	if ((pMsg->message == WM_HOTKEY) &&
		(pMsg->lParam != MAKELPARAM(MOD_WIN, 0xC5)) &&
		m_pHandler) {
		m_pHandler(this, QW_HOTKEY, (int)pMsg->wParam);
		return TRUE;
	}
	else if (pMsg->message == WM_SYSCHAR) {
		CString temp;
		temp.Format(_T("%d"), (int)this);
		VALUE vMenuBar = g_vWndToMenu.Get(temp);
		if (vMenuBar.Type() == stInteger) {
			CQMenuBar* pMenuBar = (CQMenuBar*)vMenuBar.Integer();
			if (pMenuBar != NULL) {
				if (pMenuBar->DoSysChar((TCHAR)pMsg->wParam)) {
					return 0;	// We processed the message
				}
			}
		}
	}

#ifdef UNDER_CE
	return CWnd::PreTranslateMessage(pMsg);
#else
	// Allow tabbing between window items...
	if(IsDialogMessage(pMsg)) {
		return TRUE;
	}
	else {
		return CWnd::PreTranslateMessage(pMsg);
	}
#endif
}

bool ConvertKeyCode(UINT vKey, UINT scanCode, TCHAR& ch, VALUE& vInfo)
{
/*	vInfo = AllocFrame();
	ch = '\0';

#ifndef UNDER_CE	// Still working on this stuff...

	if ((vKey == VK_SHIFT) || (vKey == VK_CONTROL) || (vKey == VK_MENU)) {
		return false;	// Only pass these keys as modifiers?
	}

	BYTE lpKeyState[256];
	char buf[2];
	GetKeyboardState(lpKeyState);
	int i = ToAscii(vKey, scanCode, lpKeyState, (WORD*)buf, 0);

	if (i == 1) {
		ch = (TCHAR)(buf[0]);
	}
	else if (i == 0) {
		switch (vKey) {
			case VK_CANCEL:		vInfo.Set(_T("break"), true);		break;
			case VK_BACK:		vInfo.Set(_T("backspace"), true);	break;
			case VK_TAB:		vInfo.Set(_T("tab"), true);			break;
			case VK_CLEAR:		vInfo.Set(_T("clear"), true);		break;
			case VK_RETURN:		vInfo.Set(_T("enter"), true);		break;
			case VK_CAPITAL:	vInfo.Set(_T("caps"), true);		break;
			case VK_ESCAPE:		vInfo.Set(_T("escape"), true);		break;
			case VK_SPACE:		ch = ' ';							break;
			case VK_PRIOR:		vInfo.Set(_T("pageup"), true);		break;
			case VK_NEXT:		vInfo.Set(_T("pagedown"), true);	break;
			case VK_END:		vInfo.Set(_T("end"), true);			break;
			case VK_HOME:		vInfo.Set(_T("home"), true);		break;
			case VK_LEFT:		vInfo.Set(_T("left"), true);		break;
			case VK_UP:			vInfo.Set(_T("up"), true);			break;
			case VK_RIGHT:		vInfo.Set(_T("right"), true);		break;
			case VK_DOWN:		vInfo.Set(_T("down"), true);		break;
			case VK_SELECT:		vInfo.Set(_T("select"), true);		break;
			case VK_INSERT:		vInfo.Set(_T("insert"), true);		break;
			case VK_DELETE:		vInfo.Set(_T("delete"), true);		break;
		}
	}

	// Lastly, add the modifier keys...
	if (GetKeyState(VK_SHIFT) & 0x8000) vInfo.Set(_T("shift"), true);
	if (GetKeyState(VK_CONTROL) & 0x8000) vInfo.Set(_T("control"), true);
	if (GetKeyState(VK_MENU) & 0x8000) vInfo.Set(_T("alt"), true);
#endif
	*/
	return true;
}

void CQWindow::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
	/*TCHAR ch;
	VALUE vInfo;
	if (m_pHandler && ConvertKeyCode(nChar, nFlags, ch, vInfo)) {
		VALUE args = AllocArray(2);
		args.Set(1, CString(ch));
		args.Set(2, vInfo);
		VALUE v = m_pHandler(this, QW_KEYPRESS, args);
		if ((v.Type() == stUndefined) || v.Boolean()) return;
	}*/
	CWnd::OnKeyDown(nChar, nRepCnt, nFlags);
}



/*struct VirtualKeyStringPair {
	UINT key;
	LPCTSTR String;
};
static VirtualKeyStringPair SpecialKeyCodes[] = {
	{VK_CANCEL,	_T("break")},
	{VK_BACK,	_T("backspace")},
	{VK_TAB,	_T("tab")},
	{VK_CLEAR,	_T("clear")},
	{VK_RETURN,	_T("enter")},
	{VK_SHIFT,	_T("shift")},
	{VK_CONTROL,_T("control")},
	{VK_MENU,	_T("alt")},
	{VK_CAPITAL,_T("caps")},
	{VK_ESCAPE,	_T("escape")},
	{VK_SPACE,	_T("space")},
	{VK_PRIOR,	_T("pageup")},
	{VK_NEXT,	_T("pagedown")},
	{VK_END,	_T("end")},
	{VK_HOME,	_T("home")},
	{VK_LEFT,	_T("left")},
	{VK_UP,		_T("up")},
	{VK_RIGHT,	_T("right")},
	{VK_DOWN,	_T("down")},
	{VK_SELECT,	_T("select")},
	{VK_SNAPSHOT, _T("printscreen")},
	{VK_HELP,	_T("help")},
};*/
